package com.hrd.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hrd.common.util.ConstantUtil;
import com.hrd.common.util.Utils;
import com.hrd.common.util.bean.ServiceResult;
import com.hrd.datasource.DatabaseContextHolder;
import com.hrd.mybatis.bean.auto.*;
import com.hrd.mybatis.bean.ext.ExtCustomModel;
import com.hrd.mybatis.mapper.auto.HrdCustomerMapper;
import com.hrd.mybatis.mapper.auto.HrdSynchLogMapper;
import com.hrd.mybatis.mapper.auto.TMLArchivesMapper;
import com.hrd.service.CommonService;
import com.hrd.service.CustomerService;
import com.hrd.service.KingDeeService;
import com.hrd.service.StatisticsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 刘江宁
 * @create 2022/1/12 17:43
 */
@Service
@Slf4j
public class CustomerServiceImpl extends BaseServiceImpl implements CustomerService {
    @Autowired
    private StatisticsService statisticsService;
    @Autowired
    TMLArchivesMapper tmlArchivesMapper;
    @Autowired
    HrdCustomerMapper hrdCustomerMapper;
    @Autowired
    CommonService commonService;

    @Autowired
    KingDeeService kingDeeService;
    @Autowired
    HrdSynchLogMapper hrdSynchLogMapper;


    @Override
    public ServiceResult<String> syncCustomerInfo() {

        //切换到mysql数据源
        DatabaseContextHolder.clearCustomerType();
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
        HrdSynchLogExample hrdSynchLogExample = new HrdSynchLogExample();
        hrdSynchLogExample.createCriteria()
                .andSynchTypeEqualTo(ConstantUtil.SYNC_TYPE_0);
        hrdSynchLogExample.setOrderByClause("synch_time desc");
        List<HrdSynchLog> hrdSynchLogs = hrdSynchLogMapper.selectByExample(hrdSynchLogExample);
        Date syncTime = new Date();

        if (hrdSynchLogs.size() == 0) {
            syncTime.setTime(0);
        } else {
            syncTime.setTime(Long.valueOf(hrdSynchLogs.get(0).getSynchTime()) * 1000);
        }

        ServiceResult<String> result = new ServiceResult<>();

        DatabaseContextHolder.clearCustomerType();
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_SQL_SERVER);
        //查询需要修改的客户信息
        /*TMLArchivesExample updateTmlArchivesExample = new TMLArchivesExample();
        updateTmlArchivesExample.createCriteria()
                .andFmodifydateGreaterThanOrEqualTo(syncTime)
                .andFitemclassidEqualTo(ConstantUtil.CUSTOMER_TYPE_ID_tMLArchives);
        List<TMLArchives> updateTmlArchives = tmlArchivesMapper.selectByExample(updateTmlArchivesExample);*/

        TMLArchivesExample createTmlArchivesExample = new TMLArchivesExample();
        createTmlArchivesExample.createCriteria()
                .andFitemclassidEqualTo(ConstantUtil.CUSTOMER_TYPE_ID_tMLArchives);
        List<TMLArchives> createTmlArchives = tmlArchivesMapper.selectByExample(createTmlArchivesExample);

        List<TMLArchives> tmlArchives = new ArrayList<>();
        /*if (CollUtil.isNotEmpty(updateTmlArchives)) {
            tmlArchives.addAll(updateTmlArchives);
        }*/
        if (CollUtil.isNotEmpty(createTmlArchives)) {
            tmlArchives.addAll(createTmlArchives);
        }


        if (tmlArchives.size() == 0) {
            result.setSuccess(false);
            result.setResult("没有可同步的数据");
            log.info("=======CustomerServiceImpl:syncCustomerInfo 客户同步没有可同步的数据========");
            return result;
        } else {
            tmlArchives = tmlArchives.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<TMLArchives>
                    (Comparator.comparing(TMLArchives::getFid))), ArrayList::new)
            );

        }
        result.setSuccess(true);
        result.setResult("同步成功");
        //构造金蝶接口参数
        String accessToken = commonService.getAccessToken().getResult();

        String url = "http://api.kingdee.com/jdy/basedata/customer_save?access_token=" + accessToken;


        for (TMLArchives t : tmlArchives) {
            try {
                JSONObject item = new JSONObject();
                item.put("number", Utils.deleteStringChar(t.getFno(), '_'));
                item.put("name", t.getFbackno().substring(t.getFbackno().length() - 4) + t.getFname());
                item.put("bankaccount", t.getFbackno());
                List<JSONObject> contactpersons = new ArrayList<>();
                JSONObject contactperson = new JSONObject();
                contactperson.put("mobile", t.getFhandphone());
                contactperson.put("contactperson", t.getFlinkname());
                contactperson.put("isdefault_linkman", true);
                contactpersons.add(contactperson);
                item.put("contactpersons", contactpersons);
                String kingDeeResult = kingDeeService.getKingDeeInterfacePost(item.toString(), url);
                JSONObject kingDeeResultObj = JSONObject.parseObject(kingDeeResult);
                log.info("=======调用金蝶传递参数=> url:{}== param:{}========", url, item.toString());
                log.info("=======金蝶返回数据:{}========", kingDeeResult);
                Boolean success = kingDeeResultObj.getBoolean("success");
                if (!success) {
                    result.setSuccess(false);
                    result.setResult("存在同步失败的数据");
                    log.info("=======CustomerServiceImpl:syncCustomerInfo 存在同步失败的数据========");

                }
                if (!kingDeeResultObj.getJSONObject("data").getBoolean("success")) {
                    result.setSuccess(false);
                    result.setResult("存在同步失败的数据");
                    log.info("=======CustomerServiceImpl:syncCustomerInfo 存在同步失败的数据========");
                    continue;
                }

                if (success && kingDeeResultObj.get("data")!=null && kingDeeResultObj.getJSONObject("data").get("successPkIds")!=null){
                    JSONArray jsonArray = kingDeeResultObj.getJSONObject("data").getJSONArray("successPkIds");
                    if (jsonArray!=null && jsonArray.size()!=0){
                        Object id = jsonArray.get(0);
                        if (id!=null){
                            DatabaseContextHolder.clearCustomerType();
                            DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);

                            HrdCustomerExample hrdCustomerExample = new HrdCustomerExample();
                            HrdCustomerExample.Criteria criteria = hrdCustomerExample.createCriteria();
                            criteria.andHrdIdEqualTo(t.getFid());
                            List<HrdCustomer> hrdCustomers = this.hrdCustomerMapper.selectByExample(hrdCustomerExample);
                            if (CollectionUtil.isNotEmpty(hrdCustomers)){
                                HrdCustomer hrdCustomer = hrdCustomers.get(0);
                                hrdCustomer.setJdId((String) id);
                                this.hrdCustomerMapper.updateByPrimaryKey(hrdCustomer);
                            }else{
                                HrdCustomer hrdCustomer = new HrdCustomer();
                                hrdCustomer.setHrdId(t.getFid());
                                hrdCustomer.setJdId((String) id);
                                hrdCustomer.setCustomerName(item.getString("name"));
                                this.hrdCustomerMapper.insert(hrdCustomer);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }


        //写入日志
        //切换到mysql数据源
        DatabaseContextHolder.clearCustomerType();
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
        HrdSynchLog hrdSynchLog = new HrdSynchLog();
        hrdSynchLog.setSynchType(ConstantUtil.SYNC_TYPE_0);
        hrdSynchLog.setSynchTime(new Date().getTime() / 1000 + "");
        hrdSynchLogMapper.insert(hrdSynchLog);
        return result;
    }

    @Override
    public Integer count(TMLArchives form) {
        DatabaseContextHolder.clearCustomerType();
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_SQL_SERVER);
        return this.extCustomMapper.selectCount(form);
    }

    @Override
    public ServiceResult<List<ExtCustomModel>> list(TMLArchives form) {
        DatabaseContextHolder.clearCustomerType();
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_SQL_SERVER);
        ServiceResult<List<ExtCustomModel>> result = new ServiceResult<>();
        List<ExtCustomModel> orderList = this.extCustomMapper.selectList(form);
        result.setSuccess(true);
        result.setResult(orderList);
        return result;
    }

    public static void main(String[] args) {
        String a = "asdasdasdasdasd1234";
        String substring = a.substring(a.length() - 4);
        System.out.println(substring);

    }

    @Override
    public void savemysql() {
        DatabaseContextHolder.clearCustomerType();
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_SQL_SERVER);
        TMLArchivesExample tmlArchivesExample = new TMLArchivesExample();
        TMLArchivesExample.Criteria criteria = tmlArchivesExample.createCriteria();
        criteria.andFitemclassidEqualTo(2145);
        List<TMLArchives> tmlArchives = this.tmlArchivesMapper.selectByExample(tmlArchivesExample);
        for (TMLArchives tmlArchive : tmlArchives) {
            System.out.println(tmlArchive.getFname());

            DatabaseContextHolder.clearCustomerType();
            DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);

            HrdCustomerExample hrdCustomerExample = new HrdCustomerExample();
            HrdCustomerExample.Criteria criteria1 = hrdCustomerExample.createCriteria();
            int i = this.hrdCustomerMapper.countByExample(hrdCustomerExample);
            if (i>0){
                continue;
            }
            if (StringUtils.isBlank(tmlArchive.getFbackno())){
                continue;
            }

            HrdCustomer hrdCustomer = new HrdCustomer();
            hrdCustomer.setHrdId(tmlArchive.getFid());
            hrdCustomer.setCustomerName(tmlArchive.getFbackno().substring(tmlArchive.getFbackno().length() - 4) + tmlArchive.getFname());
            this.hrdCustomerMapper.insert(hrdCustomer);

        }


    }

    @Override
    public void savemyJd() {
        DatabaseContextHolder.clearCustomerType();
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_MYSQL);
        HrdCustomerExample tmlArchivesExample = new HrdCustomerExample();
        HrdCustomerExample.Criteria criteria = tmlArchivesExample.createCriteria();
        List<HrdCustomer> hrdCustomers = this.hrdCustomerMapper.selectByExample(tmlArchivesExample);


        //构造金蝶接口参数
        String accessToken = commonService.getAccessToken().getResult();

        for (HrdCustomer hrdCustomer : hrdCustomers) {
            String kindDeeCustomerIdByName = kingDeeService.getKindDeeCustomerIdByName(hrdCustomer.getCustomerName(), accessToken);

        }
    }
}
